package pkg

import (
	"context"
	"sale-admin/config"

	wechat "github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/credential"
	"github.com/silenceper/wechat/v2/miniprogram"
	miniConfig "github.com/silenceper/wechat/v2/miniprogram/config"
)

type MiniProgram struct{}

func (MiniProgram) New() (*miniprogram.MiniProgram, error) {
	wc := wechat.NewWechat()
	redisOpts := &cache.RedisOpts{
		Host:     config.Config.Redis.Host + ":" + config.Config.Redis.Port,
		Password: config.Config.Redis.Password,
		Database: config.Config.Redis.Database,
	}
	redisCache := cache.NewRedis(context.Background(), redisOpts)
	wc.SetCache(redisCache)
	cfg := &miniConfig.Config{
		AppID:     config.Config.WechatMini.AppID,
		AppSecret: config.Config.WechatMini.Secret,
		Token:     "",
	}
	mp := wc.GetMiniProgram(cfg)

	mp.SetAccessTokenHandle(
		credential.NewStableAccessToken(
			config.Config.WechatMini.AppID,
			config.Config.WechatMini.Secret,
			"gowechat_officialaccount__access_token_"+config.Config.WechatMini.AppID,
			redisCache,
		),
	)
	return mp, nil
}
